<template>
  <div>
    <div style="margin-top: 20px; width: 100%">
      <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
        <div class="query-row">
          <el-form-item label="供应商编码">
            <el-input v-model="page.supplierNumber" />
          </el-form-item>
          <el-form-item label="供应商名称" style="margin-left: -20px">
            <el-input v-model="page.supplierName" />
          </el-form-item>
          <el-form-item label="供应商简介" style="margin-left: -20px">
            <el-input v-model="page.supplierProfile" />
          </el-form-item>
        </div>
        <div class="query-row">
          <el-form-item label="英文名称" style="margin-left: 20px">
            <el-input v-model="page.supplierEnglishName" />
          </el-form-item>
          <el-form-item label="是否启用:" style="margin-left: -20px">
            <el-radio-group v-model="page.isEnable">
              <el-radio label="是" :value="1" />
              <el-radio label="否" :value="0" />
            </el-radio-group>
          </el-form-item>
          <el-form-item></el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" @click="fetchData">查询</el-button>
          <el-button type="primary" @click="empty">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-button type="primary" @click="dialogFormVisible = true" style="width: 100px">新增</el-button>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="supplierNumber" label="供应商编码" />
      <el-table-column prop="supplierName" label="供应商名称" />
      <el-table-column prop="supplierAbbreviation" label="供应商简介" />
      <el-table-column prop="sid" label="供应商等级">
        <template #default="scope">
          <span v-if="scope.row.sid == 1">优质供应商</span>
          <span v-if="scope.row.sid == 2">正常</span>
          <span v-if="scope.row.sid == 3">重点关注</span>
          <span v-if="scope.row.sid == 4">劣质供应商</span>
          <span v-if="scope.row.sid == 5">黑名单</span>
        </template>
      </el-table-column>
      <el-table-column prop="supplierRating" label="供应商评分" />
      <el-table-column prop="supplierPhone" label="供应商电话" />
      <el-table-column prop="isEnable" label="是否启用">
        <template #default="scope">
          <el-text v-if="scope.row.isEnable == 0" type="primary">否</el-text>
          <el-text v-else type="primary">是</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="editItem(scope.row)">编辑</el-button>
          <el-button size="small" @click="DelFrom(scope.row.supplierId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
        :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <div>
      <el-dialog v-model="dialogFormVisible" title="添加供应商" width="1000">
        <el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" label-width="auto" class="demo-ruleForm"
          :size="formSize" status-icon>
          <el-form-item label="供应商编码" prop="supplierNumber">
            <el-input v-model="ruleForm.supplierNumber" autocomplete="off" style="width: 180px; height: 30px"
              :readonly="ruleForm.autoGenerate" clearable @click.native="handleCodeClick" />
            <template slot="prepend">R</template>
            <el-switch width="40" v-model="ruleForm.autoGenerate" active-text="自动生成" active-color="#67C23A"
              @change="handleSwitchChange" />
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="ruleForm.supplierName" />
          </el-form-item>
          <el-form-item label="供应商简称" prop="supplierAbbreviation">
            <el-input v-model="ruleForm.supplierAbbreviation" />
          </el-form-item>
          <el-form-item label="供应商英文名称" prop="supplierEnglishName">
            <el-input v-model="ruleForm.supplierEnglishName" />
          </el-form-item>
          <el-form-item label="供应商简介" prop="SupplierProfile">
            <el-input v-model="ruleForm.supplierProfile" type="textarea" />
          </el-form-item>
          <el-form-item label="供应商地址" prop="supplierAddress">
            <el-input v-model="ruleForm.supplierAddress" type="textarea" />
          </el-form-item>
          <el-form-item label="供应商等级" prop="sid">
            <el-select v-model="ruleForm.sid" placeholder="请选择供应商" size="large" filterable>
              <el-option label="优质供应商" :value="1" />
              <el-option label="正常" :value="2" />
              <el-option label="重点关注" :value="3" />
              <el-option label="劣质供应商" :value="4" />
              <el-option label="黑名单" :value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商评分" prop="supplierRating">
            <el-input-number v-model="ruleForm.supplierRating" :min="1" :max="10" />
          </el-form-item>
          <el-form-item label="供应商官网地址" prop="supplierOfficialAddress">
            <el-input v-model="ruleForm.supplierOfficialAddress" />
          </el-form-item>
          <el-form-item label="供应商邮箱地址" prop="supplierEmailAddress">
            <el-input v-model="ruleForm.supplierEmailAddress" />
          </el-form-item>
          <el-form-item label="供应商电话" prop="supplierPhone">
            <el-input v-model="ruleForm.supplierPhone" />
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="unifyCode">
            <el-input v-model="ruleForm.unifyCode" />
          </el-form-item>
          <el-form-item label="是否启用" prop="isEnable">
            <el-radio-group v-model="ruleForm.isEnable">
              <el-radio :value="true" label="是" checked>是</el-radio>
              <el-radio :value="false" label="否">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="供应商LOGO地址" prop="supplierLOGOAddress">
            <el-input v-model="ruleForm.supplierLOGOAddress" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="AddForm(ruleFormRef)">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <div>
      <el-dialog v-model="dialogFormVisible1" title="修改供应商" width="1000">
        <el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" label-width="auto" class="demo-ruleForm"
          :size="formSize" status-icon>
          <el-form-item label="供应商编码" prop="supplierNumber">
            <el-input v-model="ruleForm.supplierNumber" />
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="ruleForm.supplierName" />
          </el-form-item>
          <el-form-item label="供应商简称" prop="supplierAbbreviation">
            <el-input v-model="ruleForm.supplierAbbreviation" />
          </el-form-item>
          <el-form-item label="供应商英文名称" prop="supplierEnglishName">
            <el-input v-model="ruleForm.supplierEnglishName" />
          </el-form-item>
          <el-form-item label="供应商简介" prop="SupplierProfile">
            <el-input v-model="ruleForm.supplierProfile" type="textarea" />
          </el-form-item>
          <el-form-item label="供应商地址" prop="supplierAddress">
            <el-input v-model="ruleForm.supplierAddress" type="textarea" />
          </el-form-item>
          <el-form-item label="供应商等级" prop="sid">
            <el-select v-model="ruleForm.sid" placeholder="请选择供应商" size="large" filterable>
              <el-option label="优质供应商" :value="1" />
              <el-option label="正常" :value="2" />
              <el-option label="重点关注" :value="3" />
              <el-option label="劣质供应商" :value="4" />
              <el-option label="黑名单" :value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商评分" prop="supplierRating">
            <el-input-number v-model="ruleForm.supplierRating" :min="1" :max="10" />
          </el-form-item>
          <el-form-item label="供应商官网地址" prop="supplierOfficialAddress">
            <el-input v-model="ruleForm.supplierOfficialAddress" />
          </el-form-item>
          <el-form-item label="供应商邮箱地址" prop="supplierEmailAddress">
            <el-input v-model="ruleForm.supplierEmailAddress" />
          </el-form-item>
          <el-form-item label="供应商电话" prop="supplierPhone">
            <el-input v-model="ruleForm.supplierPhone" />
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="unifyCode">
            <el-input v-model="ruleForm.unifyCode" />
          </el-form-item>
          <el-form-item label="是否启用" prop="isEnable">
            <el-radio-group v-model="ruleForm.isEnable">
              <el-radio :value="true" label="是" checked>是</el-radio>
              <el-radio :value="false" label="否">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="供应商LOGO地址" prop="supplierLOGOAddress">
            <el-input v-model="ruleForm.supplierLOGOAddress" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible1 = false">取消</el-button>
            <el-button type="primary" @click="UpdateForm(ruleFormRef)">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import axios from 'axios';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElPagination } from 'element-plus';
import { onMounted, ref, reactive, computed } from 'vue';
const apiUrl = import.meta.env.VITE_APP_API_URL;
const tableData = ref([]);
const buderInfo = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 查询表单数据
const page = reactive({
  PageIndex: 1,
  PageSize: 10,
  totalCount: 0,
  totalPage: 0,
  supplierNumber: '',
  supplierName: '',
  supplierProfile: '',
  supplierEnglishName: '',
  isEnable: null,
});

// 整合显示、查询和分页的方法
const fetchData = () => {
  axios.get(apiUrl + '/T5/ProductInfo/ShowSupplierHandle', { params: page })
    .then((res) => {
      tableData.value = res.data.data;
      page.totalCount = res.data.totalCount;
      page.totalPage = res.data.totalPage;
    })
};

const empty = () => {
  page.supplierNumber = '',
    page.supplierName = '',
    page.supplierProfile = '',
    page.supplierEnglishName = '',
    page.isEnable = null,
    fetchData();
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  page.PageSize = val;
  fetchData();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  page.PageIndex = val;
  fetchData();
};

//逻辑删除供应商
const DelFrom = (supplierId: any) => {
  axios.put(apiUrl + '/T6/ProductInfos/DelSupplier', { SupplierId: supplierId })
    .then((res) => {
      if (res.data.code == 204) {
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
        fetchData();
      } else {
        ElMessage({
          message: '删除失败',
          type: 'error',
        })
      }
    })
}

//显示等级下拉框
// const CreateIndex = () => {
//   axios.get("http://localhost:5056/api/ProductInfo/GetSupplierLevel")
//     .then(res => {
//       buderInfo.value = res.data.data;
//     })
// }

const dialogFormVisible = ref(false)
const dialogFormVisible1 = ref(false)

// interface RuleForm {
//   supplierNumber: string
//   supplierName: string
//   supplierAbbreviation: string
//   sid: number,
//   supplierRating: number,
//   supplierPhone: string,
//   isEnable: boolean,
//   remark: string,
//   supplierEnglishName: string,
//   supplierProfile: string,
//   supplierAddress: string,
//   supplierOfficialAddress: string,
//   supplierEmailAddress: string,
//   unifyCode: string,
//   supplierLOGOAddress: string,
//   isDelete: boolean,
// }

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  supplierNumber: '',
  supplierName: '',
  supplierAbbreviation: '',
  sid: null,
  supplierRating: 0,
  supplierPhone: '',
  isEnable: true,
  remark: '',
  supplierEnglishName: '',
  supplierGrade:'',
  supplierProfile: '',
  supplierAddress: '',
  supplierOfficialAddress: '',
  supplierEmailAddress: '',
  unifyCode: '',
  supplierLOGOAddress: '',
  isDelete: false,
  autoGenerate: false, // 是否自动生成
})

const editItem = (item: RuleForm) => {
  dialogFormVisible1.value = true;
  // 复制数据到表单
  Object.assign(ruleForm, item);
};

const UpdateForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 修改为使用 axios.put 方法
      axios.put(apiUrl + "/T6/ProductInfos/UpdateSupplier", ruleForm)
        .then(res => {
          if (res.data.code === 206) {
            ElMessage.success("修改成功!");
            dialogFormVisible1.value = false;
            fetchData();
          } else {
            ElMessage.error(`修改失败: ${res.data.message || '未知错误'}`);
          }
        })
        .catch((error) => {
          console.error('修改物料产品失败:', error);
          ElMessage.error('修改物料产品失败，请稍后重试');
        });
    } else {
      console.log('error submit!', fields);
      ElMessage.error('表单验证失败，请检查输入内容');
    }
  });
};

// 生成物料产品编号（GYLX+时间戳）
const generateCode = () => {
  const timestamp = new Date().toISOString().replace(/[-:TZ]/g, "").substring(0, 14); // 获取精确到毫秒的时间戳
  ruleForm.supplierNumber = `GYS${timestamp}`;
};

const handleSwitchChange = (val: boolean) => {
  ruleForm.autoGenerate = val;
  if (val) {
    generateCode(); // 开启自动生成时立即生成
  } else {
    ruleForm.supplierNumber = ""; // 关闭时清空编号
  }
};

const handleCodeClick = () => {
  if (ruleForm.autoGenerate) {
    generateCode(); // 点击输入框时重新生成
  }
};

const AddForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post(apiUrl + "/T6/ProductInfos/AddPostSupplier", ruleForm)
        .then(res => {
          if (res.data.code == 100) {
            ElMessage.success(res.data.msg);
            ruleForm.supplierNumber = "";
          ruleForm.autoGenerate = true;
          dialogFormVisible.value = false;
          fetchData();
          } else {
            ElMessage.error("添加失败!");
          }
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

onMounted(() => {
  fetchData();
  // CreateIndex();
})
</script>

<style scoped>
.query-form {
  display: flex;
  flex-wrap: wrap;
}

.query-row {
  display: flex;
  width: 100%;
  justify-content: space-between;
  margin-bottom: 10px;
}

.query-row.el-form-item {
  flex: 1 0 calc(33.33% - 10px);
  margin-right: 10px;
}

.query-row:last-child.el-form-item:last-child {
  flex: none;
  width: 0;
}
</style>